package com.yxc.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class StockController {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    Redisson redisson;
    @RequestMapping("/deduct_stock")
    public String deductStock(){
        String lockKey="product_001";
        String clientId = UUID.randomUUID().toString();
        RLock redissonLock = redisson.getLock(lockKey);
        try {
//            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId,10, TimeUnit.SECONDS);
//            if (!result) {
//                return "error";
//            }

            redissonLock.lock(30, TimeUnit.SECONDS);
            Integer stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if(stock >0){
                stock--;
                stringRedisTemplate.opsForValue().set("stock",stock+"");
                System.out.println("扣减成功，剩余库存："+stock);
            }else{
                System.out.println("扣减失败，库存不足");
            }
        } finally {
            redissonLock.unlock();
//            if(clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))){
//                //释放锁
//                stringRedisTemplate.delete(lockKey);
//            }

        }
        return "end";
    }

}